home *** CD-ROM | disk | FTP | other *** search
- Path: mics.demon.co.uk!Bill
- From: Bill Michell <Bill@mics.demon.co.uk>
- Newsgroups: comp.lang.c++
- Subject: Re: Newbie question on these 2 constructor variations
- Date: Thu, 1 Feb 1996 20:23:33 +0000
- Organization: None
- Distribution: world
- Message-ID: <mtcFoGAFFSExEwaI@mics.demon.co.uk>
- References: <310a6256.34676691@nntp.ix.netcom.com>
- NNTP-Posting-Host: mics.demon.co.uk
- X-NNTP-Posting-Host: mics.demon.co.uk
- MIME-Version: 1.0
- X-Newsreader: Turnpike Version 1.11 <uiEOes1orVXTvvWgSAnAOBUy+p>
-
- In article <310a6256.34676691@nntp.ix.netcom.com>, "Brian F. Haddock"
- <BHaddock@ix.netcom.com> writes
- >I'm really confused on something, and can't seem to find any details
- >on the following type of constructor. Why does this type of
- >constructor work...
- >
- >CMyPropertySheet::CMyPropertySheet(LPCTSTR, CWnd* pParent, UINT)
- > : CPropertySheet("Game Options", NULL, 0)
- >
- >while this one will not?
- >
- >CMyPropertySheet::CMyPropertySheet(LPCTSTR name, CWnd* pParent, UINT
- >tmpNum)
- >{
- > name = "Game Options";
- > pParent = NULL;
- > tmpNum = 0;
- >}
- >
- >Ignoring any syntax errors I may have made typing this in, what is the
- >difference in using the ' : ' type of constructor (first example) and
- >the one that inits the fields between the brackets (second example)?
- >Are they just 2 different variations of doing the same thing?
-
- No they are not identical, though they do appear to behave identically
- (if they work)...
-
- The second version (without the colon) tries to call the default
- constructor of class CPropertySheet, and then change the default values
- stored therin. This works fine if a) a default constructor exists and b)
- the CMyPropertySheet object (or CPropertySheet object if it is a member
- of your class - though from the context, I suspect you have just derived
- your class from it) are not const.
-
- The first (working) version does not rely on the presence of a default
- constructor - it uses whatever explicit form of construction you
- specify. It also uses an initialisation, not an assignment, and so works
- fine with const objects. In (almost) all real-world cases, it will be at
- least as fast as, and possibly faster than, initialising the object and
- immediately assigning new values to it.
-
- You should always use the first form whenever possible, since it means
- people who re-use your class can declare const objects of this type,
- should they want to.
-
- So to try and express myself a little more clearly, the key difference
- is that the second example does *not* init the fields in the body of
- your code - it inits the fields by calling the default constructor of
- the parent class (or contained object) and then assigns new values to
- the member variables.
- ---
- Bill Michell eMail: Bill@mics.demon.co.uk
-